<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Index extends Stourweb_Controller
{
    private $_id = NULL;
    private $_user_info = NULL;

    /**
     * 初始化支付对象
     */
    public function before()
    {
        parent::before();
        //登录状态判断
        $this->_id = Cookie::get('st_supplier_id');
        if(empty($this->_id))
        {
            $this->request->redirect('pc/login');
        }
        else
        {
            $this->_user_info = Model_Supplier::get_supplier_byid($this->_id);
            $this->assign('userinfo',$this->_user_info);
        }

        $this->assign('cmsurl','/supplier/');
    }

    public function action_index()
    {
        if(empty($this->_user_info['authorization']) || in_array($this->_user_info['verifystatus'],array(0,1,2))){
            $link = '/supplier/pc/qualify/step';
        }else{
            $link = '/supplier/pc/index/index_data';
        }

        $this->assign('index_link',$link);
        $this->display('index');
    }

    public function action_index_data()
    {
        $account = Model_Supplier_Index::account_info($this->_id);
        $supplier_shop = Model_Supplier_Index::supplier_shop($this->_id);
        $channel = Model_Supplier_Index::channel_info($this->_id, $supplier_shop['authorization']);

        $this->assign('channel',$channel);
        $this->assign('supplier_shop',$supplier_shop);
        $this->assign('account',$account);
        $this->display('index_data');
    }

    public function action_user_info()
    {
        $token = md5(time());
        Common::session('crsf_usr_code',$token);

        $bind = DB::select()->from('supplier_zlhl')->where('supplier_id','=',$this->_id)->execute()->current();
        $is_bind = !empty($bind)?true:false;
        $this->assign('is_bind',$is_bind);
        $this->assign('frmcode',$token);
        $this->display("user_info");
    }

    /**
     * 上传用户头像
     */
    public function action_ajax_uploadface()
    {
        if (!$_FILES['Filedata'])
        {
            die ( 'Image data not detected!' );
        }
        if ($_FILES['Filedata']['error'] > 0)
        {
            switch ($_FILES ['Filedata'] ['error'])
            {
                case 1 :
                    $error_log = 'The file is bigger than this PHP installation allows';
                    break;
                case 2 :
                    $error_log = 'The file is bigger than this form allows';
                    break;
                case 3 :
                    $error_log = 'Only part of the file was uploaded';
                    break;
                case 4 :
                    $error_log = 'No file was uploaded';
                    break;
                default :
                    break;
            }
            die ( 'upload error:' . $error_log );
        }
        else
        {
            $img_data = $_FILES['Filedata']['tmp_name'];
            $size = getimagesize($img_data);
            $file_type = $size['mime'];
            if (!in_array($file_type, array('image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/gif')))
            {
                $error_log = 'only allow jpg,png,gif';
                die ( 'upload error:' . $error_log );
            }
            switch($file_type) {
                case 'image/jpg' :
                case 'image/jpeg' :
                case 'image/pjpeg' :
                    $extension = 'jpg';
                    break;
                case 'image/png' :
                    $extension = 'png';
                    break;
                case 'image/gif' :
                    $extension = 'gif';
                    break;
            }
        }
        if (!is_file($img_data))
        {
            die ( 'Image upload error!' );
        }
        //图片保存路径,默认保存在该代码所在目录(可根据实际需求修改保存路径)
        $save_path = BASEPATH;
        $file_dir = UPLOADPATH.'/member/';
        if(!is_dir($file_dir))mkdir($file_dir);
        $uinqid = uniqid();
        $litpic = '/uploads/member/'. $uinqid . '.' . $extension;
        $filename = $save_path . '/' .$litpic ;
        move_uploaded_file( $img_data, $filename );
        echo json_encode(['litpic'=>$litpic,'status'=>true]);
        exit ();
    }

    /**
     * 保存账户信息
     */
    public function action_ajax_userinfo_save()
    {
        $frmcode = Common::remove_xss(Arr::get($_POST,'frmcode'));
        $supplieid = Common::remove_xss(Arr::get($_POST,'supplierid'));

        $litpic = Common::remove_xss(Arr::get($_POST,'litpic'));
        $linkman = Common::remove_xss(Arr::get($_POST,'linkman'));
        $qq = Common::remove_xss(Arr::get($_POST,'qq'));
        $email = Common::remove_xss(Arr::get($_POST,'email'));
        $fax = Common::remove_xss(Arr::get($_POST,'fax'));

        $telephone = Common::remove_xss(Arr::get($_POST,'telephone'));
        $address = Common::remove_xss(Arr::get($_POST,'address'));
        $logo = Common::remove_xss(Arr::get($_POST,'logo'));

        $out = array();
        //安全校验码验证
        $orgcode = Common::session('crsf_usr_code');
        if($orgcode!=$frmcode)
        {
            $out['msg'] = '安全检验码错误';
            $out['status'] = 0;
            echo json_encode($out);
            exit;
        }

        $m = ORM::factory('supplier',$supplieid);
        if($m->loaded())
        {
            if (!empty($linkman))
            {
                $m->linkman = $linkman;
            }
            if (!empty($qq))
            {
                $m->qq = $qq;
            }
            if (!empty($email))
            {
                $m->email = $email;
            }
            if (!empty($litpic))
            {
                $m->litpic = $litpic;
            }
            if (!empty($telephone))
            {
                $m->telephone = $telephone;
            }
            if (!empty($fax))
            {
                $m->fax = $fax;
            }
            if (!empty($address))
            {
                $m->address = $address;
            }

            if (!empty($logo))
            {
                $m->logo = $logo;
            }

            $m->save();
            if($m->saved())
            {
                $config=[
                    'webid'=>0,
                    'cfg_qywx_admin_url_supplier_'.$supplieid=>$_POST['cfg_qywx_admin_url'],
                ];
                include BASEPATH.'/tools/classes/model/sysconfig.php';
                Model_Sysconfig::save_config($config);

                $data = array(
                    'mobile'      => $telephone,
                    'qq'          => $qq,
                    'logo'        => $litpic
                );
                if(St_Functions::is_normal_app_install('supplier_shop')){
                    $is_exist = DB::select()->from('supplier_shop')->where("supplier_id={$supplieid}")->execute()->current();
                    if($is_exist){
                        DB::update('supplier_shop')->set($data)->where("id={$is_exist['id']}")->execute();
                    }else{
                        $data['supplier_id'] = $supplieid;
                        DB::insert('supplier_shop', array_keys($data))->values(array_values($data))->execute();
                    }
                }
                $out['msg'] = '';
                $out['status'] = 1;
                echo json_encode($out);
                exit;
            }
        }
        else
        {
            $out['msg'] = __("wrong");
            $out['status'] = 0;
            echo json_encode($out);
            exit;
        }

    }

    /**
     * 企业信息
     */
    public function action_enterprise_info()
    {
        $token = md5(time());
        Common::session('crsf_usr_code',$token);

        $this->assign('frmcode',$token);

        $apply_product = array();
        $product_list = Model_Supplier::get_authorization_product_list();
        $authorization_list = explode(",", $this->_user_info["authorization"]);
        foreach ($product_list as $product)
        {
            if (in_array($product["id"], $authorization_list))
            {
                $apply_product[] = $product;
            }
        }
        $channel_list = Model_Supplier::get_ota_channel($this->_id,true);

        $this->assign('channel_list',$channel_list);
        $this->assign('apply_product',$apply_product);
        $cfg_qywx_admin_url = Model_Sysconfig::get_sys_conf('value','cfg_qywx_admin_url_supplier_'. $this->_id);
        $this->assign('cfg_qywx_admin_url',$cfg_qywx_admin_url);
        $this->display("enterprise_info");
    }

    public function action_product_list()
    {
        $type       = Arr::get($_GET,'type','');
        $page       = Arr::get($_GET,'page',1);
        $keyword    = Arr::get($_GET,'keyword','');

        $list = Model_Supplier_Index::product_list($this->_id, $type, $page, $keyword);

        echo json_encode($list);
    }

    public function action_data_report()
    {
        $params = array(
            'year'       => Arr::get($_GET,'year'),
            'month'      => Arr::get($_GET,'month'),
            'type_id'    => Arr::get($_GET,'type_id'),
            'number'     => Arr::get($_GET,'number'),
            'product_id' => Arr::get($_GET,'product_id'),
            'channel_id' => Arr::get($_GET,'channel_id'),
        );

        /*获取筛选条件*/
        $filter_criteria = Model_Supplier_Index::filter_criteria($this->_id);

        /*获取曲线统计数据*/
        $params['number'] = $params['type_id']==0?0:$params['number'];
        if($params['product_id'] && $params['type_id']){
            $table = St_Functions::table_field($params['type_id']);
            $product = DB::select('id','title')->from($table[3])->where("id={$params['product_id']}")->execute()->current();
            $this->assign('product',$product);
        }
        $data_statistics = Model_Supplier_Index::data_statistics($this->_id, $params);
        /*获取圆形统计数据*/
        $channel_statistics = Model_Supplier_Index::channel_statistics($this->_id, $params);
        /*获取渠道*/
        $channel_list = Model_Supplier::get_ota_channel($this->_id,true);

        //var_dump($data_statistics,$channel_statistics);exit;
        $this->assign('channel_list',$channel_list);
        $this->assign('channel_statistics',$channel_statistics);
        $this->assign('data_statistics',$data_statistics);
        $this->assign('params',$params);
        $this->assign('filter_criteria',$filter_criteria);
        $this->display('data_report');
    }

    // 保存上传的logo
    public function  action_ajax_logo_save()
    {
        $filedata = Arr::get($_FILES, 'filedata');
        if(!$filedata)
        {
            $filedata=Arr::get($_FILES, 'file');
        }
        $storepath = UPLOADPATH . '/supplier/logo/';
        if (!file_exists($storepath))
        {
            mkdir($storepath,0777,true);
        }
        $filename = uniqid();
        $out = array();
        $ext = end(explode('.', $filedata['name']));

        if (move_uploaded_file($filedata['tmp_name'], $storepath . $filename . '.' . $ext))
        {
            $out['status'] = 1;
            $out['litpic'] = '/uploads/supplier/logo/' . $filename . '.' . $ext;
        }
        else
        {
            $out['status'] = 0;
            $out['msg'] = '上传失败,图片大小不得超过2M';
        }
        echo json_encode($out);
    }

    public function action_ajax_zlhl_bind()
    {
        $account = $_POST['account'];
        $password = $_POST['password'];
        try {
            $model = ORM::factory('supplier_zlhl')->where('supplier_id', '=', $this->_id)->find();
            if ($model->loaded()) {
                throw new Exception('已绑定过');
            }
            $url = Zlhl::$_service_url . Zlhl::$_bind_supplier_path;

            $params = array('account' => $account, 'password' => $password);
            $result = Zlhl::request_api($url, $params);

            if (empty($result) ) {
                throw new Exception('绑定失败');
            }
            if($result['status']!=1)
            {
                throw new Exception($result['msg']);
            }
            $model2 = ORM::factory('supplier_zlhl')->where('zlhl_member_id', '=', $result['data']['memberid'])->find();
            if ($model2->loaded())
            {
                throw new Exception('该智联互联账号已绑定到其他供应商账号');
            }

            $model->supplier_id = $this->_id;
            $model->zlhl_member_id = $result['data']['memberid'];
            $model->addtime = time();
            $model->save();

            $this->install_all_app( $result['data']['memberid']);
            $response = array('status'=>1,'msg'=>'保存成功');
            echo json_encode($response);
        }
        catch(Exception $e)
        {
            $result = array('status'=>0,'msg'=>$e->getMessage());
            echo json_encode($result);
        }
        //$model->addtime =
    }
}